#!/usr/bin/env python
# -*- coding:utf-8 -*-

from app import db
import math
import json
from sqlalchemy import or_

from models.passageInfoModel import PassageInfo
from utils import commons
from utils.response_code import RET, error_map_EN, error_map_CN
from utils.loggings import loggings


class PassageInfoController(PassageInfo):

    # add
    @classmethod
    def add(cls, **kwargs):
        
        try:
            model = PassageInfo(
                PostAuthorID=kwargs.get('PostAuthorID'),
                PostContent=kwargs.get('PostContent'),
                PostTitle=kwargs.get('PostTitle'),
                PostStatus=kwargs.get('PostStatus'),
                PostType=kwargs.get('PostType'),
                DeptType=kwargs.get('DeptType'),
                UpVoteNum=kwargs.get('UpVoteNum'),
                CommentNum=kwargs.get('CommentNum'),
                LookNUM=kwargs.get('LookNUM'),
                HeadlineEntities=kwargs.get('HeadlineEntities'),
                BodyEntities=kwargs.get('BodyEntities'),
                CreateTime=kwargs.get('CreateTime'),
                ModifyTime=kwargs.get('ModifyTime'),
                
            )
            db.session.add(model)
            db.session.commit()
            results = commons.query_to_dict(model)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # get
    @classmethod
    def get(cls, **kwargs):
        try:
            filter_list = [cls.IsDelete == 0]
            if kwargs.get('AutoID'):
                filter_list.append(cls.AutoID == kwargs.get('AutoID'))
            else:
                if kwargs.get('PostAuthorID'):
                    filter_list.append(cls.PostAuthorID == kwargs.get('PostAuthorID'))
                if kwargs.get('PostContent'):
                    filter_list.append(cls.PostContent == kwargs.get('PostContent'))
                if kwargs.get('PostTitle'):
                    filter_list.append(cls.PostTitle == kwargs.get('PostTitle'))
                if kwargs.get('PostStatus') is not None:
                    filter_list.append(cls.PostStatus == kwargs.get('PostStatus'))
                if kwargs.get('PostType') is not None:
                    filter_list.append(cls.PostType== kwargs.get('PostType'))
                if kwargs.get('DeptType') is not None:
                    filter_list.append(cls.DeptType== kwargs.get('DeptType'))
                if kwargs.get('UpVoteNum') is not None:
                    filter_list.append(cls.UpVoteNum == kwargs.get('UpVoteNum'))
                if kwargs.get('CommentNum') is not None:
                    filter_list.append(cls.CommentNum == kwargs.get('CommentNum'))
                if kwargs.get('LookNUM') is not None:
                    filter_list.append(cls.LookNUM == kwargs.get('LookNUM'))
                if kwargs.get('HeadlineEntities') is not None:
                    filter_list.append(cls.HeadlineEntities == kwargs.get('HeadlineEntities'))
                if kwargs.get('BodyEntities') is not None:
                    filter_list.append(cls.BodyEntities == kwargs.get('BodyEntities'))
                if kwargs.get('CreateTime'):
                    filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
                if kwargs.get('ModifyTime'):
                    filter_list.append(cls.ModifyTime == kwargs.get('ModifyTime'))
                
            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))
            
            passage_info_info = db.session.query(cls).filter(*filter_list)
            
            count = passage_info_info.count()
            pages = math.ceil(count / size)
            passage_info_info = passage_info_info.limit(size).offset((page - 1) * size).all()

            # judge whether the data is None
            if not passage_info_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No query results'}
                
            results = commons.query_to_dict(passage_info_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}
            
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # delete
    @classmethod
    def delete(cls, **kwargs):
        try:
            filter_list = [cls.IsDelete == 0]
            if kwargs.get('AutoID'):
                primary_key_list = []
                for primary_key in str(kwargs.get('AutoID')).replace(' ', '').split(','):
                    primary_key_list.append(cls.AutoID == primary_key)
                filter_list.append(or_(*primary_key_list))
                
            else:
                if kwargs.get('PostAuthorID'):
                    filter_list.append(cls.PostAuthorID == kwargs.get('PostAuthorID'))
                if kwargs.get('PostContent'):
                    filter_list.append(cls.PostContent == kwargs.get('PostContent'))
                if kwargs.get('PostTitle'):
                    filter_list.append(cls.PostTitle == kwargs.get('PostTitle'))
                if kwargs.get('PostStatus') is not None:
                    filter_list.append(cls.PostStatus == kwargs.get('PostStatus'))
                if kwargs.get('PostType') is not None:
                    filter_list.append(cls.PostType== kwargs.get('PostType'))
                if kwargs.get('DeptType') is not None:
                    filter_list.append(cls.PostType== kwargs.get('DeptType'))
                if kwargs.get('UpVoteNum') is not None:
                    filter_list.append(cls.UpVoteNum == kwargs.get('UpVoteNum'))
                if kwargs.get('CommentNum') is not None:
                    filter_list.append(cls.CommentNum == kwargs.get('CommentNum'))
                if kwargs.get('LookNUM') is not None:
                    filter_list.append(cls.LookNUM == kwargs.get('LookNUM'))
                if kwargs.get('HeadlineEntities') is not None:
                    filter_list.append(cls.HeadlineEntities == kwargs.get('HeadlineEntities'))
                if kwargs.get('BodyEntities') is not None:
                    filter_list.append(cls.BodyEntities == kwargs.get('BodyEntities'))
                if kwargs.get('CreateTime'):
                    filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))
                if kwargs.get('ModifyTime'):
                    filter_list.append(cls.ModifyTime == kwargs.get('ModifyTime'))
                
            res = db.session.query(cls).filter(*filter_list).with_for_update().update({'IsDelete': 1})
            if res < 1:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to delete'}
                
            db.session.commit()
            return {'code': RET.OK, 'message': error_map_EN[RET.OK]}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # update
    @classmethod
    def update(cls, **kwargs):
        try:
            
            res = db.session.query(cls).filter(
                cls.AutoID == kwargs.get('AutoID'),
                cls.IsDelete == 0
            ).with_for_update().update(kwargs)
            
            if res < 1:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}
            db.session.commit()
            
            return {'code': RET.OK, 'message': error_map_EN[RET.OK]}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # ------------------------------------------- Api漏洞缺陷 6 示例接口： 批量分配 ------------------------------------------
    # update_vulnerability_6
    @classmethod
    def update_vulnerability_6(cls, **kwargs):
        try:
            # Api漏洞缺陷 6 示例接口： 批量分配
            print(kwargs)
            if kwargs.get('PostTitle', False):
                return {'code': RET.MASS, 'message': error_map_CN[RET.MASS], 'error': 'Mass distribution'}

            res = db.session.query(cls).filter(
                cls.AutoID == kwargs.get('AutoID'),
                cls.IsDelete == 0
            ).with_for_update().update(kwargs)

            if res < 1:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}
            db.session.commit()

            return {'code': RET.OK, 'message': error_map_EN[RET.OK]}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    # batch add
    @classmethod
    def add_list(cls, **kwargs):
        param_list = json.loads(kwargs.get('PassageInfoList'))
        model_list = []
        for param_dict in param_list:
            
            model = PassageInfo(
                PostAuthorID=param_dict.get('PostAuthorID'),
                PostContent=param_dict.get('PostContent'),
                PostTitle=param_dict.get('PostTitle'),
                PostStatus=param_dict.get('PostStatus'),
                PostType=param_dict.get('PostType'),
                DeptType=param_dict.get('DeptType'),
                UpVoteNum=param_dict.get('UpVoteNum'),
                CommentNum=param_dict.get('CommentNum'),
                LookNUM=param_dict.get('LookNUM'),
                CreateTime=param_dict.get('CreateTime'),
                ModifyTime=param_dict.get('ModifyTime'),
                
            )
            model_list.append(model)
        
        try:
            db.session.add_all(model_list)
            db.session.commit()
            results = []
            for model in model_list:
                results.append(commons.query_to_dict(model))
            
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()
